/**
 *
 * @author John Creecy
 */

package battlebarnapplet;

import battlebarnapplet.entities.PlayerLocationEntity;
import java.io.IOException;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class StateListener implements Runnable {

	public StateListener() {
	}

	public void run() {
		socketMonitor();
	}

	public void socketMonitor() {
		try {
			String packetData = "";
			String packetMessage = "";
			String hatMessages = "";
			long packetTimeStamp = 0;
			String playerName;
			int xLoc = 0;
			int yLoc = 0;
			DatagramSocket serverSocket = new DatagramSocket(10000);
			Board board = new Board();
			while (true) {
				byte[] receiveData = new byte[1024];
				try {
					DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
					serverSocket.receive(receivePacket);
					packetData = new String(receivePacket.getData());
					InetAddress sourceIp = receivePacket.getAddress();
					// 1282706243753
					packetTimeStamp = Long.parseLong(packetData.substring(0, 13));
					//if (packetTimeStamp > Main.lastPacketTime) {
						xLoc = Integer.parseInt(packetData.substring(13, 16));
						yLoc = Integer.parseInt(packetData.substring(16, 19));
						playerName = packetData.substring(19);

						// player locs
						PlayerLocationEntity playerLocationEntity = new PlayerLocationEntity(xLoc, yLoc);
						board.playerLocs.put(playerName, playerLocationEntity);

						Main.lastPacketTime = packetTimeStamp;
					//}
				} catch (SocketException ex) {
					System.out.println(ex);
				} catch (IOException ex) {
					System.out.println(ex);
				}
			}
		} catch (SocketException ex) {
			Logger.getLogger(StateListener.class.getName()).log(Level.SEVERE, null, ex);
		}
	}
}
